package MicroRpc.framework.protocol.http;

import MicroRpc.framework.beans.Invoker;
import MicroRpc.framework.redis.Registry.LocalRegistry;
import MicroRpc.framework.tools.IO.IOtool;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class HttpHandler {

    public static void handler(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletInputStream ips = req.getInputStream();
        try {
            Invoker invoker = (Invoker) new ObjectInputStream(ips).readObject();
            String interfaceName = invoker.getInterfaceName();
            Class serviceImpl = LocalRegistry.getImpl(interfaceName);
            try {
                Object o = serviceImpl.newInstance();
                Method method = serviceImpl.getMethod(invoker.getMethodName(), invoker.getParamsType());

                Object result = method.invoke(o, invoker.getParams());

                IOtool.write(result, resp.getOutputStream());

            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}
